package com.cctc.juc.common.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * [线程池优雅关闭] 钩子函数执行线程。
 */
public class ShutdownHookThread extends Thread {
    private volatile boolean hasShutdown = false;
    private static AtomicInteger shutdownTimes = new AtomicInteger(0);
    private final Callable callback;

    public ShutdownHookThread(String name, Callable callback) {
        super("JVM 进程退出钩子[终止 (" + name + ")]");
        this.callback = callback;
    }

    @Override
    public void run() {
        synchronized (this) {
            if (!this.hasShutdown) {
                this.hasShutdown = true;
                long beginTime = System.currentTimeMillis();
                try {
                    this.callback.call();
                } catch (Exception e) {
                    System.out.println(getName() + " error: " + e.getMessage());
                }
                long execTime = System.currentTimeMillis() - beginTime;
                System.out.println(getName() + " 耗时: " + execTime + " 毫秒！！！");
            }
        }
    }
}
